﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace MotivLogger.LogMethods
{
    class XmlLog : ILogMethod
    {     
        private ISetting LoggerSettings;
        public void Log(MotivLogger.LogLevels Level, string body, string Actor)
        {
            if (!File.Exists(Actor + ".xml"))
            {
                XmlWriter writer = XmlWriter.Create(Actor + ".xml");
                writer.WriteStartElement("EVENTS");
                writer.WriteEndElement();
                writer.Flush();
                writer.Close();
            }
            AddRecord(new List<string> { Level.ToString(),Actor, body, DateTime.Now.ToString()});
        }


        void AddRecord(List<string> newData)  
    {  
    string[] tagName =
      new string[] { "Level", "Actor", "body", "date" };
    FileStream fStream;
    XmlDocument xmlDoc;

    
        //create the reader filestream (fs)   
    using (fStream = new FileStream(newData[1] + ".xml", FileMode.Open,  
           FileAccess.Read, FileShare.ReadWrite))  
        {  
            //Create the xml document   
            xmlDoc = new XmlDocument();  
  
            //Load the xml document   
            xmlDoc.Load(fStream);  
  
            //Close the fs filestream   
            fStream.Close();  
        }  
    
   

          XmlElement newitem;  
          XmlElement newOUTERitem =   
          xmlDoc.CreateElement("event");  
  
        for (int i = 0; i < tagName.Length; i++)  
        {  
            newitem = xmlDoc.CreateElement(tagName[i]);  
            newitem.InnerText = newData[i];  
            newOUTERitem.AppendChild(newitem);  
        }  
          xmlDoc.DocumentElement.InsertAfter(  
          newOUTERitem, xmlDoc.DocumentElement.LastChild);  
          FileStream WRITER = new FileStream(newData[1] + ".xml",   
          FileMode.Truncate, FileAccess.Write,   
          FileShare.ReadWrite);  
          xmlDoc.Save(WRITER);  
          WRITER.Close();  
  

}  

        public void Stop() { ;}
    }
}
